package com.class_;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取类对象
        Class<?> cls = Class.forName("java.io.File");
        // 得到所有的File构造器
        Constructor<?>[] declaredConstructors = cls.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println("File构造器：" + declaredConstructor);
        }

        /*  传统方法：
         *  File file = new File("D:\\mynew.txt");
         *  file.createNewFile();
         * */
        // 得到指定的File构造器
        System.out.println("===============================================");
        Constructor<?> deCon = cls.getDeclaredConstructor(String.class);
        String filePath = "D:\\mynew.txt";
        // 创建文件对象
        Object o = deCon.newInstance(filePath);
        // 得到createNewFile方法的对象
        Method method = cls.getDeclaredMethod("createNewFile");
        method.invoke(o);  // 反射调用方法
        System.out.println("创建成功");
    }
}